<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 原内容列调整为16列 -->
      <el-col :span="17">
        <!-- 筛选条件 -->
        <el-form inline class="filter-container">
          <el-form-item>
            <el-radio-group v-model="type">
              <el-radio-button :label="0" :value="0">我管理的</el-radio-button>
              <el-radio-button :label="1" :value="1">我发起的</el-radio-button>
              <el-radio-button :label="2" :value="2">我负责的</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="任务状态">
            <el-checkbox-group v-model="filter.status">
              <el-checkbox-button v-for="item in statusOptions" :key="item.value" :label="item.value"
                :value="item.value">{{ item.label }}</el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="所属项目">
            <el-select v-model="filter.grpId" placeholder="所属项目" clearable>
              <el-option v-for="item in projectOptions" :key="item.WTG_ID" :label="item.WTG_Title"
                :value="item.WTG_ID" />
            </el-select>
          </el-form-item>

          <el-form-item label="搜索">
            <el-input v-model="filter.title" placeholder="模糊搜索" clearable />
          </el-form-item>
          <el-form-item>
            <el-button @click="r => { filter.pageIndex = 1; getTasks() }">搜索</el-button>
            <el-button type="primary" @click="showPublishDialog">发布任务</el-button>

          </el-form-item>
          <el-form-item>
            <GroupManage @updated="getMyGroups"></GroupManage>
          </el-form-item>
        </el-form>

        <!-- 任务表格 -->
        <el-table :data="tasks" border style="width: 100%" height="calc(100vh - 400px)">
          <el-table-column prop="WTG_Title" label="所属项目" width="100" />
          <el-table-column prop="WT_Status" label="状态" width="80">
            <template slot-scope="{row}">
              <el-tag :type="getStatus(row.WT_Status, row).tabType">{{ getStatus(row.WT_Status, row).label }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="WT_Title" label="标题" width="*" />
          <el-table-column prop="PublisherName" label="发布人" width="100" />
          <el-table-column prop="HandlerName" label="开发负责人" width="100" />
          <el-table-column prop="WT_Score" label="分值" width="80" />
          <el-table-column prop="WT_CreateTime" label="发布时间" width="120">
            <template slot-scope="{row}">
              {{ formatDate(row.WT_CreateTime) }}
            </template>
          </el-table-column>
          <el-table-column label="预计完成时间" width="120">
            <template slot-scope="{row}">
              {{ formatDate(row.WT_PredictFinish) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="{row}">
              <el-button type="text" size="mini" @click="currentTaskId = row.WT_ID">查看</el-button>
              <el-button v-if="row.CanConrirm" type="text" size="mini"
                @click="confirmTask = { ID: row.WT_ID, PredictTime: row.WT_RequireTime, ...{ row } }; confirmTaskVis = true">接受</el-button>
              <el-button v-if="row.CanReject" type="text" size="mini" @click="rejectTask(row)">撤回</el-button>
              <el-button v-if="row.CanCancle" type="text" size="mini" @click="cancleTask(row)">取消</el-button>
              <el-button v-if="row.CanSubmit" type="text" size="mini" @click="submitTask(row)">提交验收</el-button>
              <el-button v-if="row.CanCheckPass" type="text" size="mini" @click="checkPass(row)">通过验收</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div>
          <el-pagination :current-page.sync="filter.pageIndex" :page-size.sync="filter.pageSize" :total="taskTotal"
            @size-change="getTasks" @current-change="getTasks" />
        </div>
      </el-col>

      <!-- 新增统计列 -->
      <el-col :span="7">
        <div class="stats-panel">
          <!-- 项目统计 -->
          <!--el-card shadow="hover" class="stats-card">
            <div slot="header" class="clearfix">
              <span>项目统计</span>
            </div>
            <div class="stat-item">
              <div class="stat-label">总项目数</div>
              <div class="stat-value">{{ projectCount }}</div>
            </div>
          </el-card-->

          <!-- 任务统计 -->
          <el-card shadow="hover" class="stats-card">
            <div slot="header" class="clearfix">
              <span>我的任务统计</span>
              <el-button icon="el-icon-refresh-left" circle @click="getStatistic"></el-button>
            </div>

            <!-- 我发起的 -->
            <div class="stat-section">
              <h4>我发起的任务</h4>
              <div>
                <div class="status-item" v-for="stat in statistic.publishs" :key="'dev-' + stat.Status">
                  <el-tag :type="getStatus(stat.Status).tabType" style="width: 80px;margin-right:50px">
                    {{ getStatus(stat.Status).label }}
                  </el-tag>
                  <span class="count">{{ stat.Count }}</span>
                </div>
              </div>
              <!--div class="status-item" v-for="stat in myTaskStats" :key="'my-' + stat.status">
                <el-tag :type="statusType[stat.status]">{{ statusText[stat.status] }}</el-tag>
                <span class="count">{{ stat.count }}</span>
              </div-->
            </div>

            <!-- 我负责的 -->
            <div class="stat-section">
              <h4>我负责的任务</h4>
              <div>
                <div class="status-item" v-for="stat in statistic.handles" :key="'dev-' + stat.Status">
                  <el-tag :type="getStatus(stat.Status).tabType" style="width: 80px;margin-right:50px">
                    {{ getStatus(stat.Status).label }}
                  </el-tag>
                  <span class="count">{{ stat.Count }}</span>
                </div>
              </div>
              <!--div class="status-item" v-for="stat in myDevelopStats" :key="'dev-' + stat.status">
                <el-tag :type="statusType[stat.status]">{{ statusText[stat.status] }}</el-tag>
                <span class="count">{{ stat.count }}</span>
              </div-->
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
    <!-- 量发布任务对话框 -->
    <el-dialog title="批量发布任务" :visible.sync="dialogVisible" width="1000px" top="50px">
      <el-form :model="newTask" :rules="formRules" ref="taskForm" label-width="120px">
        <!-- 公共信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属项目" prop="project">
              <el-select v-model="newTask.WT_Group" placeholder="请选择项目" style="width:100%">
                <el-option v-for="item in managedGrps" :key="item.WTG_ID" :label="item.WTG_Title"
                  :value="item.WTG_ID" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开发负责人" prop="developer">
              <el-select v-model="newTask.WT_PrincipalEmpId" placeholder="请选择负责人" style="width:100%"
                @changed="getAddingTaskGrpUsers">
                <el-option v-for="user in canChoseUser" :key="user.WTGU_EmpId" :label="user.USR_Name"
                  :value="user.WTGU_EmpId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div style="height: calc(100vh - 360px);overflow-y: auto;">
          <!-- 任务列表 -->
          <div v-for="(task, index) in newTask.tasks" :key="task.WT_ID" class="task-item">
            <el-divider content-position="left">任务 {{ index + 1 }}</el-divider>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item :label="'标题'" :prop="'tasks.' + index + '.WT_Title'" :rules="formRules.title">
                  <el-input v-model="task.WT_Title" placeholder="请输入标题" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="'预计完成'" :prop="'tasks.' + index + '.WT_RequireTime'" :rules="formRules.dueTime">
                  <el-date-picker v-model="task.WT_RequireTime" type="date" value-format="yyyy-MM-dd 00:00:00"
                    placeholder="选择时间" style="width:100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8" class="operation-col">
                <el-button type="danger" icon="el-icon-remove" circle @click="removeTask(index)"
                  v-if="newTask.tasks.length > 1" />
              </el-col>
            </el-row>
            <el-form-item :label="'任务内容'" :prop="'tasks.' + index + '.WT_Description'" :rules="formRules.content">
              <el-input v-model="task.WT_Description" type="textarea" :rows="2" :maxlength="1000"
                placeholder="请输入任务详情" />
            </el-form-item>
          </div>

          <div class="add-task">
            <el-button type="primary" icon="el-icon-plus" @click="addTask">添加任务</el-button>
          </div>
        </div>
      </el-form>

      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitTasks">发布任务</el-button>
      </div>
    </el-dialog>
    <el-dialog title="确认任务" :visible.sync="confirmTaskVis" width="600px">
      <div>
        <el-form label-width="100px" v-if="confirmTask">
          <el-form-item label="预计完成日期">
            <el-date-picker type="date" v-model="confirmTask.PredictTime" value-format="yyyy-MM-dd 23:59:59" />
          </el-form-item>
          <el-form-item label="任务分值">
            <el-input v-model="confirmTask.Score" type="number" placeholder="请输入任务分值" />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="doConfirmTask">确认</el-button>
      </div>
    </el-dialog>

    <taskForm :taskId.sync="currentTaskId"></taskForm>

  </div>
</template>

<script>
import { GetGroups, AddGroup, AddTasks, GetMyManage, GetMyPublish, GetMyPrincipal, GetMyHandle, ConfirmTask, RejectTask, CancleTask, GetGroupUsers, SubmitTask, CheckPass, GetStatistic, GetMyGroups } from '@/api/task/workTaskManageApi.js'
import { getLastDateOfMonth } from '@/utils/datetime.js'
import moment from 'moment/moment'
import GroupManage from './components/groupManage.vue'
import taskForm from './components/taskForm.vue'
export default {
  components: { GroupManage, taskForm },
  data() {
    return {
      type: 0,//0:我管理的； 1：我负责的；2：我发布的
      filter: {
        pageIndex: 1,
        pageSize: 15,
        grpId: -1,
        status: [1, 2, 3, 6],
        query: '',
        from: '2022-01-01',
        to: '2026-12-31'
      },
      tasks: [

      ],
      taskTotal: 0,
      newTask: {
        WT_Group: '',
        developer: '',
        tasks: [this.emptyTask()]
      },
      dialogVisible: false,
      managedGrps: [],
      groups: [],
      statusOptions: [
        { value: 1, label: '新发布', tabType: 'success' },
        { value: 2, label: '开发中', tabType: 'warning' },
        { value: 3, label: '待审核', tabType: 'warning' },
        { value: 4, label: '已完成', tabType: 'default' },
        { value: 6, label: '撤回', tabType: 'danger' }
      ],

      formRules: {
        WT_Group: [
          { required: true, message: '请选择项目', trigger: 'change' }
        ],
        WT_PrincipalEmpId: [
          { required: true, message: '请选择负责人', trigger: 'change' }
        ],
        WT_Title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        WT_Description: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ],
        WT_RequireTime: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ]
      },
      groupRules: {
        WTG_Title: [
          { required: true, message: '请输入项目名称', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (this.groups.some(g => g.WTG_Title === value)) {
                callback(new Error('项目名称已存在'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
      },
      canChoseUser: [],
      projectDialogVisible: false,
      projectCount: 0,
      statistic: { handles: [], publishs: [] },
      currentTaskId: null,

      confirmTask: null,
      confirmTaskVis: false
    }
  },
  computed: {
    filteredTasks() {
      return this.tasks.filter(task => {
        return (!this.filter.project || task.project === this.filter.project) &&
          (!this.filter.status || task.status === this.filter.status) &&
          (!this.filter.title || task.title.includes(this.filter.title))
      })
    },
    // 修改原有项目选项计算属性
    projectOptions() {
      let prjs = [{ WTG_ID: -1, WTG_Title: '全选' }, ...this.groups]
      return prjs
    }

  },
  watch: {
    type() {
      this.filter.pageIndex = 1
      this.getTasks()
    },
    'filter.status': function () {
      this.filter.pageIndex = 1
      this.getTasks()
    },
    'newTask.WT_Group': function () {
      this.getAddingTaskGrpUsers()
    },
    seletedPrj: function () {
      GetGroupUsers(this.seletedPrj.WTG_ID).then(r => {
        this.grpUsers = r.data
      })
    }
  },
  methods: {
    getStatus: function (status, row) {
      console.log('s', status, row)
      let s = this.statusOptions.find(s => s.value == status)
      if (s == null) {
        return { value: -100, label: "未知:" + status, }
      }
      s = { ...s }
      if (s.label == '待审核' && row && row.WT_CheckPassUsers) {
        let usrs = JSON.parse(row.WT_CheckPassUsers)
        if (usrs.length > 0) {
          s.label = '部分通过'
        }
      }
      return s;
    },
    getAddingTaskGrpUsers() {
      if (this.newTask && this.newTask.WT_Group) {
        GetGroupUsers(this.newTask.WT_Group).then(r => {
          this.canChoseUser = r.data.filter(s => s.TR_CanHandle)
        })
      }
      else {
        this.canChoseUser = []
      }
    },
    getMyGroups() {
      GetMyGroups().then(response => {
        this.managedGrps = response.data.managed
        this.groups = response.data.groups
      })
    },

    showPublishDialog() {
      this.newTask = {
        project: '',
        developer: '',
        tasks: [this.emptyTask()]
      }
      this.dialogVisible = true
    },
    publishTask() {
      this.tasks.push({
        ...this.newTask,
        id: Date.now(),
        publisher: '当前用户', // 实际应用中替换为真实用户
        developer: '',
        status: 0,
        createTime: new Date().toLocaleString()
      })
      this.dialogVisible = false
    },
    doConfirmTask() {
      this.$confirm('确认接受任务？').then(r => {
        ConfirmTask(this.confirmTask).then(r => {
          this.getTasks()
          this.getStatistic()
          this.confirmTaskVis = false
          this.confirmTask = null
        })
      })
    },
    submitTask(task) {
      this.$confirm('确定提交验收？').then(r => {
        SubmitTask({ WTL_WorkTaskId: task.WT_ID, WTL_Remark: '完成请验收' }).then(r => {
          this.getTasks()
          this.getStatistic()
        })
      })
    },
    checkPass(task) {
      this.$confirm('确定验收通过？').then(r => {
        CheckPass({ WTL_WorkTaskId: task.WT_ID, WTL_Remark: '验收通过' }).then(r => {
          this.getTasks()
          this.getStatistic()
        })
      })
    },
    rejectTask(task) {
      this.$confirm('确定撤回任务？').then(r => {
        RejectTask({ WTL_WorkTaskId: task.WT_ID, WTL_Remark: '撤回任务' }).then(r => {
          this.getTasks()
          this.getStatistic()
        })
      })
    },
    cancleTask(task) {
      this.$confirm('确定取消任务？').then(r => {
        CancleTask({ WTL_WorkTaskId: task.WT_ID, WTL_Remark: '取消任务' }).then(r => {
          this.getTasks()
          this.getStatistic()
        })
      })
    },
    emptyTask() {
      return {
        WT_Title: '',
        WT_Description: '',
        WT_RequireTime: getLastDateOfMonth()
      }
    },
    addTask() {
      this.newTask.tasks.push(this.emptyTask())
    },
    removeTask(index) {
      this.newTask.tasks.splice(index, 1)
    },
    submitTasks() {
      if (this.newTask && this.newTask.tasks.length) {
        this.newTask.tasks.forEach(e => {
          e.WT_PrincipalEmpId = this.newTask.WT_PrincipalEmpId
          e.WT_Group = this.newTask.WT_Group
        });
        AddTasks(this.newTask).then(r => {
          this.$message.success('任务提交成功');
          this.getTasks()
          this.getStatistic()
        })
      }

    },
    getTasks() {
      let sts = JSON.stringify(this.filter.status);
      switch (this.type) {
        case 0: {
          GetMyManage(
            this.filter.pageIndex,
            this.filter.pageSize,
            sts,
            this.filter.from,
            this.filter.to,
            this.filter.grpId)
            .then(r => {
              this.tasks = r.data.Items
              this.taskTotal = r.data.Total
            })
          break;
        }
        case 1: {
          GetMyPublish(
            this.filter.pageIndex,
            this.filter.pageSize,
            sts,
            this.filter.from,
            this.filter.to,
            this.filter.grpId)
            .then(r => {
              this.tasks = r.data.Items
              this.taskTotal = r.data.Total
            })
          break;
        }
        case 2: {
          GetMyPrincipal(
            this.filter.pageIndex,
            this.filter.pageSize,
            sts,
            this.filter.from,
            this.filter.to,
            this.filter.grpId)
            .then(r => {
              this.tasks = r.data.Items
              this.taskTotal = r.data.Total
            })
          break;
        }

      }
    },
    formatDate(date) {
      if (date && date.length > 10) {
        return moment(date).format('YYYY-MM-DD')
      }
    },
    getStatistic() {
      GetStatistic().then(r => {
        this.statistic = r.data
      })
    }
  },
  mounted() {
    this.getMyGroups()
    this.getTasks()
    this.getStatistic()
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.el-select,
.el-input {
  width: 100%;
}

/* 新增样式 */
.el-table--scrollable-y {
  margin-top: 15px;
}
</style>